﻿using Microsoft.AspNetCore.Http;
using SaaS.Cache.Sites;
using SaaS.Core;
using SaaS.Model.Dto.Sites;
using System;
using System.Collections.Generic;
using System.Text;
using XCore.Dependency;

namespace Web.Admin
{
    public static class SlaveSetting
    {
        private static readonly IHttpContextAccessor _httpContextAccessor;
        private static readonly SiteCacheService _siteCacheService;
        private static IDictionary<string, string> _SlaveCache = new Dictionary<string, string>();
        static SlaveSetting()
        {
            _httpContextAccessor = IocCollection.Resolve<IHttpContextAccessor>();
            _siteCacheService = IocCollection.Resolve<SiteCacheService>();
        }
        /// <summary>
        /// 获取站点对应的连接字符串
        /// </summary>
        /// <returns></returns>
        public static string GetConnectionString()
        {
            if (_httpContextAccessor == null) return CoreSetting.DefaultConnectionString;
            HostString host = _httpContextAccessor.HttpContext.Request.Host;
            string domain = host.Value.Substring(host.Value.IndexOf("."));
            if (!_SlaveCache.ContainsKey(domain))
            {
                int siteId = _siteCacheService.GetSiteId(domain);
                SiteModel site = _siteCacheService.GetSiteInfo(siteId);
                lock (_SlaveCache)
                {
                    if (site.IsHost)
                    {
                        _SlaveCache.Add(domain, site.ConnectionString);
                    }
                    else
                    {
                        _SlaveCache.Add(domain, CoreSetting.DefaultConnectionString);
                    }
                }
            }
            return _SlaveCache[domain];
        }
    }
}
